package com.solar.passwordsafe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;

import com.db4o.*;
import com.db4o.config.Configuration;
import com.db4o.query.Predicate;
import com.db4o.query.Query;

public class Db4oHelper {
	
	private static final String TAG="Db4oHelper";
	
	private Context context;
	private String db;
	private static ObjectContainer oc=null;
	
	public Db4oHelper(Context context,String db) {
		this.context=context;
		this.db=db;
	}
	
	private Configuration dbConfig() {
		Configuration c=Db4o.newConfiguration();		
		c.objectClass(PassEntry.class).objectField("id").indexed(true);
		return c;		
	}
	
	private String dbFullPath(Context ctx,String db) {
		return ctx.getDir("data", 0).getPath()+"/"+ db;
	}
	
	private ObjectContainer db() {
		try {
			if(oc==null||oc.ext().isClosed())
				oc=Db4o.openFile(dbConfig(), dbFullPath(context,db));
			return oc;
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			return null;
		}
	}
	
	public void close() {
		if(oc!=null)
			oc.close();
	}
	
	public void storePassword(PassEntry entry) {
		if(entry.getId()==0)
			entry.setId(getNextId());
		db().store(entry);
		db().commit();
	}
	
	public ObjectSet getPasswordsById(long id) {
		PassEntry pe=new PassEntry(id);
		return db().queryByExample(pe);
	}
	
	public void deletePassword(long id) {
		ObjectSet res=getPasswordsById(id);
		while (res.hasNext()) {
			db().delete((PassEntry)res.next());			
		}
		db().commit();
	}
	
	public ObjectSet getAllPasswords() {
		Query query=db().query();
		query.constrain(PassEntry.class);
		query.descend("id").orderAscending();
				
		return query.execute();
	}
	
	public List<PassEntry> fetchAllRows() {
		ArrayList<PassEntry> rows=new ArrayList<PassEntry>();
		ObjectSet os=getAllPasswords();
		while (os.hasNext()) {
			rows.add((PassEntry)os.next());
		}		
		return rows;
	}
	
	public PassEntry getPasswordById(long id) {
		ObjectSet res=getPasswordsById(id);
		if(res.hasNext())
			return (PassEntry)res.next();
		else {
			return null;
		}
	}
	
	public int passwordCount() {
		return getAllPasswords().size();
	}
	
	public long getNextId() {
		ObjectSet<IncrementedId> res=db().query(IncrementedId.class);
		IncrementedId ii=null;
		long nextId;
		
		if(res.hasNext())
			ii=(IncrementedId)res.next();
		else {
			ii=new IncrementedId();
		}
		
		nextId=ii.getNextId();
		db().store(ii);
		return nextId;		
	}
}
